let express = require('express');
let router = express.Router();
let fs = require('fs');
router.use(express.urlencoded({ extended: true }));
router.get('/login', (req, res) => {
    let abc = fs.readFileSync('./login.html', 'utf-8');
    res.send(abc)
})
router.get('/register', (req, res) => {
    let abc = fs.readFileSync('./register.html', 'utf-8');
    res.send(abc)
})
router.post('/dologin', (req, res) => {
    if (req.body.username == "" || req.body.password == "") {
        res.send("请输入用户名或者密码");
        //return 为了结束js逻辑
        return;
    }
    let data = fs.readFileSync("./persons.json", "utf-8");
    //把字符串转化为数组
    let arr = JSON.parse(data);
    //通过findIndex 查找下标索引 找到了就是 已注册
    let index = arr.findIndex(
        (item) =>
            item.username == req.body.username && item.password == req.body.password
    );
    if (index == -1) {
        res.send("未找到用户名");
    } else {
        res.send("登录成功");
    }
})
router.post('/doregister', (req, res) => {
    if (req.body.username == "" || req.body.password == "") {
        res.send("请输入用户名或者密码");
        //return 为了结束js逻辑
        return;
    }
    //如果不为空
    // console.log(req.body);
    //读取person.json文件
    let data = fs.readFileSync("./persons.json", "utf-8");
    //'[{"username":"xm1","password":"1234"},{"username":"xm2","password":"222"},{"username":"xm3","password":"333"}]'
    /* 
  [
    { username: 'xm1', password: '1234' },
    { username: 'xm2', password: '222' },
    { username: 'xm3', password: '333' }
  ]
  */
    //    console.log( JSON.parse(data) ,'ddd');
    //把字符串转化为数组
    let arr = JSON.parse(data);
    //通过findIndex 查找下标索引 找到了就是 已注册
    let index = arr.findIndex(
        (item) =>
            item.username == req.body.username && item.password == req.body.password
    );
    if (index == -1) {
        arr.push(req.body);
        fs.writeFileSync("./persons.json", JSON.stringify(arr));
        res.send("注册 成功");
    } else {
        res.send("当前用户名已注册，请换个名字");
    }
})
module.exports = router;